const express = require ('express');
const router = express.Router ();
const db = require ('../../db'); // 引入数据库封装模块
const $sql = require ('../../sqlMap');
const moment = require ('moment');
/* GET 获取文章列表 page. */
// 查询文章列表
router
  .get ('/article/articleList', function (req, res, next) {
    let sql = $sql.article.SELECT;
    db.query (sql, function (err, result) {
      if (result) {
        for (item in result) {
          result[item].createTime = moment (result[item].createTime).format (
            'YYYY-MM-DD HH:mm:ss'
          );
        }
        return db.jsonWrite (res, {data: result});
      }
    });
  })
  /**
     * 新增文章
     */
  .post ('/article/add', (req, res) => {
    let sql = $sql.article.ADD;
    let params = req.body;
    let require = db.hasAllRequired (params, ['title', 'content']);
    if (require.require) {
      db.query (
        sql,
        [
          params.title,
          params.content,
          moment (new Date ()).format ('YYYY-MM-DD HH:mm:ss'),
        ],
        function (result, fields) {
          if (result) {
            db.jsonWrite (res, {data: result});
          }
        }
      );
    }
  })
  /**
	* 删除用户
 */
  .post ('/article/del', (req, res) => {
    let param = req.body;
    let require = db.hasAllRequired (req.body, ['id']);
    if (require.require) {
      db.query ($sql.article.DEL, [param.id], (result, fields) => {
        if (result.affectedRows > 0) {
          res.json ({code: 0, data: {}, msg: '删除用户成功！'});
        } else {
          res.json ({code: 1, data: {}, msg: '用户不存在！'});
        }
      });
    }
  })
  .post ('/article/update', (req, res) => {
    let sql = $sql.article.UPDATE;
    let params = req.body;
    let require = db.hasAllRequired (params, ['title', 'content']);
    if (require.require) {
      db.query (
        sql,
        [
          params.title,
          params.content,
          moment (new Date ()).format ('YYYY-MM-DD HH:mm:ss'),
          params.id,
        ],
        function (result, fields) {
          if (result) {
            db.jsonWrite (res, {data: result});
          }
        }
      );
    }
  });
module.exports = router;
